#include "../source/server.hpp"

#include <iostream>

using namespace std;

void HandleClose(Channel *channel)
{
    std::cout << "close: " << channel->Fd() << std::endl;
    channel->Remove(); // 移除清空
    delete channel;
}

void HandleRead(Channel *channel)
{
    int fd = channel->Fd();
    char buffer[1024] = {0};
    int ret = recv(fd, buffer, 1023, 0);
    if (ret <= 0)
    {
        return HandleClose(channel); // 关闭释放
    }
    std::cout << buffer << std::endl;
    channel->EnableWrite(); // 启动可写事件
}

void HandleWrite(Channel *channel)
{
    int fd = channel->Fd();
    const char *str = "nihao";
    int ret = send(fd, str, strlen(str), 0);
    if (ret < 0)
    {
        return HandleClose(channel);
    }
    channel->DisableWrite(); // 关闭写监控
}

void HandleError(Channel *channel)
{
    return HandleClose(channel);
}

void HandleEvent(Channel *channel)
{
    std::cout << "有了一个事件!!!" << std::endl;
    // DBG_LOG("有了一个事件!!!");
}

// void Accept(Poller *poller, Channel *server_channel)
void Accept(EventLoop *loop, Channel *server_channel)
{
    int server_fd = server_channel->Fd();
    int newfd = accept(server_fd, NULL, NULL);
    if (newfd < 0)
        return;
    // Channel *new_channel = new Channel(poller, newfd);
    Channel *new_channel = new Channel(loop, newfd);
    new_channel->SetReadCallback(std::bind(HandleRead, new_channel)); // 为新的通信套接字设置可读事件的回调函数
    new_channel->SetWriteCallback(std::bind(HandleWrite, new_channel));
    new_channel->SetCloseCallback(std::bind(HandleClose, new_channel));
    new_channel->SetErrorCallback(std::bind(HandleError, new_channel));
    new_channel->SetEventCallback(std::bind(HandleEvent, new_channel));
    new_channel->EnableRead();
}

int main(void)
{
    // Poller poller; // 管理多个 Channel 的类
    EventLoop loop;
    Socket server;
    server.CreateServer(8500);
    // 为监听套接字，创建一个Channel进行事件的管理，以及事件的处理
    Channel channel(&loop, server.Fd());
    channel.SetReadCallback(std::bind(Accept, &loop, &channel)); // 回调中，获取新连接，并未新连接创建Channel，并添加监控
    channel.EnableRead();
    while (true)
    {
        // std::vector<Channel *> actives;
        // poller.Poll(&actives);

        // // for (auto &it : actives)
        // // it->HandleEvent();

        // for (int i = 0; i < actives.size(); i++)
        // {
        //     // std::cout << actives[i]->Fd() << "    ";
        //     actives[i]->HandleEvent();
        // }

        // 联合测试 Channel，Poller 和 EventPoller 的时候，只需要调用 EventLoop 类里面的 start 函数的哦
        loop.start();

        sleep(1);
    }
    server.Close();

    return 0;
}
